package com.avcompris.util;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;
import static com.google.common.collect.Iterables.toArray;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * closure-like utilities.
 * 
 * @author David Andriana Copyright Avantage Compris SARL 2009-2010 ©
 */
public abstract class RowClosureUtils extends AbstractUtils {

	/**
	 * go through a collection, apply a closure-with-return, and return
	 * the array containing all the returned values.
	 * 
	 * @return the collected valued.
	 */
	public static <T, E extends Exception> String[] collect(
			final T[] array,
			final RowClosureWithReturn<String, T, E> closure) throws E {

		nonNullArgument(array, "array");
		nonNullArgument(closure, "closure");

		final String[] result = new String[array.length];

		for (int i = 0; i < array.length; ++i) {

			result[i] = closure.execute(array[i]);
		}

		return result;
	}

	/**
	 * go through a collection, apply a closure-with-return, and return
	 * the array containing all the returned values.
	 * 
	 * @return the collected valued.
	 */
	public static <T, E extends Exception> String[] collect(
			final Collection<T> collection,
			final RowClosureWithReturn<String, T, E> closure) throws E {

		nonNullArgument(collection, "collection");
		nonNullArgument(closure, "closure");

		final List<String> result = new ArrayList<String>();

		for (final T it : collection) {

			result.add(closure.execute(it));
		}

		return toArray(result, String.class);
	}
}
